package com.projectfile.service;

import com.projectfile.dao.LoginMapper;
import com.projectfile.entity.LoginUser;
import com.projectfile.entity.Role;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class CustomUserService implements UserDetailsService {
    @Resource
    private LoginMapper loginMapper;

    @Override
    public UserDetails loadUserByUsername(String username) { //重写loadUserByUsername 方法获得 userdetails 类型用户

        LoginUser user = loginMapper.findByUserName(username);
        System.out.println(user.getUser_id()+"  xxxxxxxxxxxxxxxxx");
        if(user == null){
            throw new UsernameNotFoundException("不存在");
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for(Role role : user.getRoles())
        {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
            System.out.println(role.getName());
        }
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        return new org.springframework.security.core.userdetails.User(user.getUsername(),
                user.getPassword(), authorities);
    }
}
